package jwt

import (
	"errors"
	"github.com/golang-jwt/jwt/v4"
	"time"
)

// User 声明自己的 key
type User struct {
	ID       uint   `json:"id"`
	Username string `json:"username"`
	Role     int    `json:"role"`
}

type UserClaims struct {
	// 内嵌标准的声明
	User
	jwt.RegisteredClaims
}

// GenUserToken
// 生成 token
func GenUserToken(user User, accessSecret string, expires int64) (string, error) {
	userClaim := UserClaims{
		User: user,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * time.Duration(expires))), // 定义到期时间
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, userClaim)
	tokenString, err := token.SignedString([]byte(accessSecret))
	if err != nil {
		return "", err
	}
	return tokenString, err
}

// ParseToken
// 解析 token
func ParseToken(tokenString string, accessSecret string, expires int64) (*UserClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(accessSecret), nil
	})

	if err != nil {
		return nil, err
	}
	// token.Claims.(*UserClaims) 内存断言 是否存在错误
	if claims, ok := token.Claims.(*UserClaims); ok && token.Valid {
		return claims, nil
	}
	return nil, errors.New("invalid token")
}
